'use strict';

const Controller = require('./base');

class ArticleController extends Controller {
  async test() {
    this.success('test');
  }

  async getList() {
    try {
      const { ctx } = this;
      const from = Number(ctx.query.from) || 0;
      const size = Number(ctx.query.size) || 20;

      const articleHits = await ctx.service.article.selectList(from, size);
      const categoryMap = await ctx.service.category.getCategoryMap();

      const result = articleHits.map(item => ({
        ...item._source,
        content: item._source.content.slice(0, 150) + '...',
        first_category_text: categoryMap[item._source.first_category],
        second_category_text: categoryMap[item._source.second_category],
      }));
      this.success(result);
    } catch (err) {
      this.error(`获取文章列表失败，${err}`);
    }
  }

  async search() {
    try {
      const { ctx } = this;
      const keyword = ctx.query.keyword;

      const articleHits = await ctx.service.article.selectByKeyword(keyword);
      const categoryMap = await ctx.service.category.getCategoryMap();

      const result = articleHits.map(item => ({
        id: item._source.id,
        title: item._source.title,
        first_category: item._source.first_category,
        second_category: item._source.second_category,
        first_category_text: categoryMap[item._source.first_category],
        second_category_text: categoryMap[item._source.second_category],
      }));
      this.success(result);
    } catch (err) {
      this.error(`搜索文章失败，${err}`);
    }
  }

  async selectNameByCategory() {
    try {
      const { ctx } = this;
      const first_category = ctx.query.first_category || '';

      const hits = await ctx.service.article.selectNameByCategory(first_category);
      const result = hits.reduce((total, item) => {
        const body = item._source;
        const arr = total[body.second_category];
        if (arr) {
          arr.push({
            id: body.id,
            title: body.title,
          });
        } else {
          total[body.second_category] = [{
            id: body.id,
            title: body.title,
          }];
        }
        return total;
      }, {});
      this.success(result);
    } catch (err) {
      this.error(`获取数据失败，${err}`);
    }
  }

  async getItem() {
    try {
      const { ctx } = this;
      const id = ctx.params.id;

      const result = await ctx.service.article.selectById(id);
      const categoryMap = await ctx.service.category.getCategoryMap();

      result.first_category_text = categoryMap[result.first_category];
      result.second_category_text = categoryMap[result.second_category];

      this.success(result);
    } catch (err) {
      this.error(`获取文章失败，${err}`);
    }
  }
}

module.exports = ArticleController;
